Skip to main content

Removing all elements

var arr = [1, 2, 3, 4];

Method 1

Creates a new array and overwrites the existing array reference with a new one.

arr = [];

Care must be taken as this does not remove any items from the original array. The array may have been closed over when passed to a function. The array will remain in memory for the life of the function though you may not be aware of this. This is a common source of memory leaks.

Example of a memory leak resulting from bad array clearing:

var count = 0;
function addListener(arr) { // arr is closed over
var b = document.body.querySelector("#foo" + (count++)); b.addEventListener("click", function(e) { // this functions reference keeps
// the closure current while the
// event is active
// do something but does not need arr
}); }
arr = ["big data"]; var i = 100;
while (i > 0) {
addListener(arr); // the array is passed to the function
arr = []; // only removes the reference, the original array remains array.push("some large data"); // more memory allocated
i--;
}
// there are now 100 arrays closed over, each referencing a different array
// no a single item has been deleted

To prevent the risk of a memory leak use the one of the following 2 methods to empty the array in the above example's while loop.

Method 2

Setting the length property deletes all array element from the new array length to the old array length. It is the most efficient way to remove and dereference all items in the array. Keeps the reference to the original array

arr.length = 0;

Method 3

Similar to method 2 but returns a new array containing the removed items. If you do not need the items this method is inefficient as the new array is still created only to be immediately dereferenced.

arr.splice(0); // should not use if you don't want the removed items
// only use this method if you do the following
var keepArr = arr.splice(0); // empties the array and creates a new array containing the
// removed items